import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import GeneratorView from '../views/system/generator/GneratorView.vue'
import GeneratorTemplateView from '@/views/system/generator/GeneratorTemplateView.vue'
import GeneratorStepFormView from '@/views/system/generator/form/GeneratorStepFormView.vue'
import GeneratorTemplateStepFormView from '@/views/system/generator/form/GeneratorTemplateFormView.vue'
import GeneratorPreviewView from '@/views/system/generator/GeneratorPreviewView.vue'
import CacheView from '@/views/system/cache/SysDatabaseCacheView.vue'
import SysUserView from '@/views/system/user/SysUserView.vue'
import SysRoleView from '@/views/system/role/sysRoleView.vue'
import LoginView from '@/views/LoginView.vue'
import SysMenuView from '@/views/system/menu/sysMenuView.vue'
import SysPermissionView from '@/views/system/permission/sysPermissionView.vue'
import type { SysMenu } from '@/api/sysMenu/sysMenu.d'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    {
      path: '/',
      name: 'home',
      component: HomeView,
      children: []
    }
    /*     {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue')
    } */
  ]
})


//addRouter 添加路由
export const addRouter = (menu: SysMenu) => {
  if (!menu.isSubMenu) {
    router.addRoute('home', {
      path: menu.url!,
      name: menu.menuName!,
      props: true,
      component: () => import((`../views${menu.componentPath}`))
    })
  }
  if (menu.children) {
    menu.children.forEach(value => addRouter(value))
  }
}

router.beforeResolve((to, from, next) => {
  if (to.path === '/login') {
    next()
    sessionStorage.clear()
    return
  }
  const token = localStorage.getItem('token')
  if (!token) {
    next({ path: '/login', replace: true })
  }
  next()
})

export default router
